package com.ztgf.shopping.service.shop;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopSysInvoiceMapper;
import com.ztgf.shopping.models.bo.shop.ShopSysInvoiceBO;
import com.ztgf.shopping.models.bo.shop.ShopSysInvoiceQueryBO;
import com.ztgf.shopping.models.bo.shop.ShopSysInvoiceSaveBO;
import com.ztgf.shopping.models.dto.shop.ShopInvoiceHeadDTO;
import com.ztgf.shopping.models.dto.shop.ShopSysInvoiceDTO;
import com.ztgf.shopping.models.service.shop.IShopInvoiceHeadService;
import com.ztgf.shopping.models.service.shop.IShopSysInvoiceService;
import com.ztgf.shopping.models.vo.shop.ShopSysInvoiceApplyVO;
import com.ztgf.shopping.models.vo.shop.ShopSysInvoiceRelevanceVO;
import com.ztgf.shopping.models.vo.shop.ShopSysInvoiceVO;
import com.ztgf.sys.models.constant.SysConstant;
import com.ztgf.sys.models.dto.SysConfigDTO;
import com.ztgf.sys.models.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 店铺平台开票控制器
 *
 * @author liyang
 * @Date 2021-05-26 12:08:14
 */
@DubboService
@Slf4j
public class ShopSysInvoiceServiceImpl extends ServiceImpl<ShopSysInvoiceMapper, ShopSysInvoiceDTO> implements IShopSysInvoiceService{

    @Resource
    private YmlConfig ymlConfig;

    @DubboReference
    private IShopInvoiceHeadService shopInvoiceHeadService;
    @DubboReference
    private ISysConfigService sysConfigService;

    @Override
    public boolean add(ShopSysInvoiceSaveBO saveBO) {
        ShopSysInvoiceDTO dto = new ShopSysInvoiceDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 买家或者卖家申请开票列表
     * @param bo
     * @return
     */
    @Override
    public Page<ShopSysInvoiceVO> queryPageList(ShopSysInvoiceBO bo) {
        Page<ShopSysInvoiceVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<ShopSysInvoiceVO> vos = new ArrayList<>();
        ShopSysInvoiceVO shopSysInvoiceVO = baseMapper.queryPriceNot(bo);
        if (bo.getMoldType () == 0) { //查询类型 0按明细查询，1按月份查询
            vos = baseMapper.queryPageList(page, bo);
        }else if(bo.getMoldType () == 1){//查询类型 0按明细查询，1按月份查询
            Integer not = 1;
            Integer all = null;
            Integer already = 0;
            List<ShopSysInvoiceVO> vosnNot = new ArrayList<>();
            vosnNot = baseMapper.queryPageListByMonth(page, bo,not);
            for (ShopSysInvoiceVO shopSysInvoiceVO1: vosnNot) {
                ShopSysInvoiceVO vo = new ShopSysInvoiceVO ();
                vo.setTime (shopSysInvoiceVO1.getTime ());
                vo.setPriceNot (shopSysInvoiceVO1.getPrice ());
                try {
                    Date month = new SimpleDateFormat ("yyyy-MM").parse(shopSysInvoiceVO1.getTime ());
                    ShopSysInvoiceVO voAll = new ShopSysInvoiceVO ();
                    ShopSysInvoiceVO voAlready = new ShopSysInvoiceVO ();
                    voAll = baseMapper.queryPageListPrice(page, bo,month,all);
                    vo.setPriceAll (voAll.getPrice ());
                    voAlready = baseMapper.queryPageListPrice(page, bo,month,already);
                    if(voAlready != null){
                        vo.setPriceAlready (voAlready.getPrice ());
                    }else {
                        vo.setPriceAlready (new BigDecimal (0));
                    }
                } catch (ParseException e) {
                    log.info ("时间格式有误==================" + e );
                }
                vos.add(vo);
            }

//              ----------------------------------------------------------------------------------------
//            List<ShopSysInvoiceVO> vosAll = new ArrayList<>();
//            Integer allStatus = null;
//            Integer alreadyStatus = 0;
//            Integer notStatus = 1;
//            vosAll = baseMapper.queryPageListByMonth(page, bo,allStatus);
//            for (ShopSysInvoiceVO shopSysInvoiceVO1: vosAll) {
//                ShopSysInvoiceVO vo = new ShopSysInvoiceVO ();
//                vo.setTime (shopSysInvoiceVO1.getTime ());
//                vo.setPriceAll (shopSysInvoiceVO1.getPrice ());
//                try {
//                    Date month = new SimpleDateFormat ("yyyy-MM").parse(shopSysInvoiceVO1.getTime ());
//                    ShopSysInvoiceVO voAready = new ShopSysInvoiceVO ();
//                    ShopSysInvoiceVO voNot = new ShopSysInvoiceVO ();
//                    voAready = baseMapper.queryPageListPrice(page, bo,month,alreadyStatus);
//                    if(voAready != null){
//                        vo.setPriceAlready (voAready.getPrice ());
//                    }else {
//                        vo.setPriceAlready (new BigDecimal (0));
//                    }
//                    voNot = baseMapper.queryPageListPrice(page, bo,month,notStatus);
//                    if(voNot != null){
//                        vo.setPriceNot (voNot.getPrice ());
//                    }else {
//                        vo.setPriceNot (new BigDecimal (0));
//                    }
//                } catch (ParseException e) {
//                    log.info ("时间格式有误==================" + e );
//                }
//                vos.add(vo);
//            }

        }
        for (ShopSysInvoiceVO vo2: vos) {
            if (shopSysInvoiceVO != null){
                vo2.setPriceAllNot (shopSysInvoiceVO.getPriceAllNot ());
            }else {
                vo2.setPriceAllNot (new BigDecimal (0));
            }
        }
        page.setRecords(vos);
        return page;
    }

    @Override
    public List<ShopSysInvoiceRelevanceVO> selectVOS(Long id) {
        List<ShopSysInvoiceRelevanceVO> vos = new ArrayList<>();
        vos = baseMapper.selectVOS(id);
        return vos;
    }

    @Override
    public List<ShopSysInvoiceVO> selectByMonth(Date date, Long shopId,Integer priceType,Integer sellOrBuyType) {
        return baseMapper.selectByMonth(date, shopId,priceType,sellOrBuyType);
    }

    @Override
    public Result<ShopSysInvoiceApplyVO> applyInvoice(ShopSysInvoiceQueryBO bo) {
        ShopSysInvoiceApplyVO vo = new ShopSysInvoiceApplyVO ();
        BigDecimal price = new BigDecimal (0);
        String name = "";
        if (bo.getMoldType () == 0 ){ //查询类型 0按明细查询，1按月份查询
            List<ShopSysInvoiceVO> vos = new ArrayList<>();
            vos = baseMapper.applyInvoice(bo);
            if(CustomizeUtil.listIsNotNull (vos)){
                name = vos.get (0).getName ();
                for (ShopSysInvoiceVO shopSysInvoiceVO:vos) {
                    price = price.add(shopSysInvoiceVO.getPrice ());
                }
            }

        }
        if(bo.getMoldType () == 1 && bo.getTimes ()!=null ){ //查询类型 0按明细查询，1按月份查询
            if (bo.getTimes () !=null && bo.getTimes ()!= ""){
                String[] split = bo.getTimes ().split (",");
                for (String time :split) {
                    try {
                        Date date = new SimpleDateFormat ("yyyy-MM").parse(time);
                        List<ShopSysInvoiceVO> vos = baseMapper.applyInvoiceByMonth(date,bo);
                        log.info ("按月查询集合+++++++++vos" + JSON.toJSONString (vos));
                        if(CustomizeUtil.listIsNotNull (vos)){
                            name = vos.get (0).getName ();
                            for (ShopSysInvoiceVO shopSysInvoiceVO: vos) {
                                price = price.add(shopSysInvoiceVO.getPrice ());
                            }
                        }

                    } catch (ParseException e) {
                        log.info ("时间格式有误==================" + e );
                    }
                }
            }
        }
        ShopInvoiceHeadDTO adminHeadDTO = shopInvoiceHeadService.selectByType (); //获取admin发票信息
        vo.setName (name);
        vo.setPrice (price);
        vo.setInvoicePrice (price);
        vo.setSpecialTaxRate (SysConstant.COMMON_TAX_RATE);
        vo.setCommonTaxRate (SysConstant.COMMON_TAX_RATE);
        vo.setAdminInvoiceCompanyName (adminHeadDTO.getName ());
        vo.setAdminTaxpayerId (adminHeadDTO.getTaxpayerId ());
        vo.setAdminCompanyAdress (adminHeadDTO.getCompanyAdress ());
        vo.setAdminCompanyPhone (adminHeadDTO.getCompanyPhone ());
        vo.setAdminBankAddress (adminHeadDTO.getBankAddress ());
        vo.setAdminBankCardNo (adminHeadDTO.getBankCardNo ());

        //判断金额是否小于最低开票金额
        SysConfigDTO sysConfigDTO = sysConfigService.selectById (2);
        if (sysConfigDTO != null){
            String minStr = sysConfigDTO.getValue ();
            BigDecimal min = new BigDecimal(minStr);
            if (min.compareTo(price) > 0){
                CodeEnum.FAIL_100071.setMsg ("金额不能低于开票最低金额,最低开票金额为:" + min + "元。");
                return new Result<> (CodeEnum.FAIL_100071);
            }
        }

        return new Result<> (vo);
    }
}
